package com.mmy.fta.trade.server.websocket;

/**
 * @author qiang.lin
 * @since 2021/11/6
 */
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.Session;

public class SessionPool {

    public static Map<String, Session> sessions = new ConcurrentHashMap<String, Session>();

    public static void close(String sessionId) throws IOException {
        for(String openId : SessionPool.sessions.keySet())
        {
            Session session = SessionPool.sessions.get(openId);
            if(session.getId().equals(sessionId))
            {
                sessions.remove(openId);
                break;
            }
        }
    }

    public static void sendMessage(String sessionId , String message) {
        sessions.get(sessionId).getAsyncRemote().sendText(message);
    }

    public static void sendMessage(String message) {
        for(String sessionId : SessionPool.sessions.keySet())
        {
            SessionPool.sessions.get(sessionId).getAsyncRemote().sendText(message);
        }
    }


    public static void sendMessage(Map<String, Object> params) {
        //  {"fromUserId": userId,"toUserId": toUserId,"msg": msg};
        String toOpenId = params.get("toOpenId").toString();
        String msg = params.get("msg").toString();
        String fromOpenId = params.get("fromOpenId").toString();
        msg = "来自" + fromOpenId + "的消息：" + msg;
        Session session = sessions.get(toOpenId);
        if(session != null)
        {
            session.getAsyncRemote().sendText(msg);
        }
    }
}
